import 'dotenv/config';
import http from 'http';
import fs from 'fs/promises';
import url from 'url';
import path from 'path';
import { Http2ServerResponse } from 'http2';

const __filename = url.fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

console.log(__dirname, __filename);

const PORT = process.env.PORT;


const server = http.createServer(async(req,res) => {

    try{
        if(req.method === 'GET') {
            let filePath;
            if(req.url==='/'){
                filePath=path.join(__dirname,'public','index.html');
            } else if (req.url==='/about'){
                filePath=path.join(__dirname,'public','about.html');
            } else {
                res.writeHead(404,{'Content-Type': 'text/html;charset=utf-8'});
                res.end('<h1>484 无法找到此页<h1>');
                return;
            }

            const data=await fs.readFile(filePath);
            res.setHeader('Centent-Type','text/html;charset=utf-8');
            res.writeHead(200);
            res.end(data);

        } else {
            res.writeHead(400,{'Centent-Type':'text/html;charset=utf-8'});
            res.end('非法请求');
        }
    }catch (error){
        console.log(error);
        res.writeHead(500,{'Content-Type':'text/html;charset=utf-8'});
        res.end('<h1>服务器错误<h1>');
    }
    
});

server.listen(PORT,() => {
    console.log(`服务器已启动，监听端口8000${PORT}`);
});